using AutoMapper;
using ShopForWeb.Models;
using Microsoft.EntityFrameworkCore;
using ShopForWeb.Dto.ViewModels;
using Microsoft.Extensions.Configuration;

namespace ShopForWeb.Service;

public class CommodityService : BaseService
{


  public CommodityService(ShopDbContext context, IConfiguration configuration, IMapper mapper) : base(context, configuration, mapper)
  {
    // _context = context;
    // _mapper = mapper;
  }
  //（分页）查页号，一页记录数
  public async Task<List<CommodityViewModel>> GetByPageAsync(int skip, int take, string key)
  {
    this.UseSlaveDB();
    var commodity = await _context.Commoditys
                         .Where(p => EF.Functions.Like(p.Cm_name, $"%{key}%"))
                         .OrderByDescending(p => p.CommodityID)
                         .Skip(skip).Take(take)
                         .AsNoTracking()
                         .ToListAsync();
    return _mapper.Map<List<CommodityViewModel>>(commodity);
  }

  public async Task<int> GetCountAsync(string key)
  {
    return await _context.Commoditys
                         .Where(p => EF.Functions.Like(p.Cm_name, $"%{key}%"))
                         .CountAsync();
  }

  public async Task<int> AddNewAsync(CommodityViewModel pvm)
  {
    var p = _mapper.Map<Commodity>(pvm);
    _context.Entry<Commodity>(p).State = EntityState.Added;
    return await _context.SaveChangesAsync();
  }

  //修改
  public async Task<CommodityViewModel?> GetByIDAsync(int commodityID)
  {
    var p = await _context.Commoditys.Where(p => p.CommodityID == commodityID)
                    .FirstOrDefaultAsync();

    if (p == null)
      return null;

    return _mapper.Map<CommodityViewModel>(p);
  }

  public async Task<int> ModifyAsync(CommodityViewModel pvm)
  {
    var p = _mapper.Map<Commodity>(pvm);
    _context.Entry<Commodity>(p).State = EntityState.Modified;
    return await _context.SaveChangesAsync();
  }


  //删除
  public async Task<int> RemoveAsync(int commodityID)
  {
    _context.Commoditys.Remove(new Commodity()
    {
      CommodityID = commodityID
    });
    return await _context.SaveChangesAsync();

  }
}
